package com.electric.qrapp.ui.base.frg

import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.ColorRes
import androidx.annotation.LayoutRes
import androidx.annotation.MainThread
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleObserver
import com.electric.qrapp.ui.base.act.SimpleActivity
import com.electric.qrapp.ui.base.vm.BaseViewModel

import com.electric.qrapp.utils.view.LoadingUtils

/*
 *@author created by WA03675
 *@date  2021-08-02 13:38
 *@des
 */

abstract class SimpleFragment : Fragment() {
    @Suppress
    protected val mContext: Context by lazy { requireContext() }


    val loadingUtils: LoadingUtils by lazy {
        LoadingUtils()
    }


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = defaultInflater(inflater, container)
        initFirst(view)
        return view
    }

    @LayoutRes
    abstract fun getLayoutId(): Int


    abstract fun getBaseVM(): BaseViewModel?

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setBarColor()
        initView(view)
        initListener()
        initData()
        initNetListener()
    }

    abstract fun initListener()


    protected open fun initFirst(view: View) {}

    abstract fun initView(view: View)


    protected open fun defaultInflater(inflater: LayoutInflater, container: ViewGroup?): View =
        inflater.inflate(getLayoutId(), container, false)


    abstract fun initData()


    @MainThread
    fun addObserver(observer: LifecycleObserver) {
        lifecycle.addObserver(observer)
    }

    private fun initNetListener() {
        getBaseVM()?.run {
            loadingLiveDate.observe(viewLifecycleOwner) {
                loadingUtils.showLoading(context, it)
            }
        }
        lifecycle.addObserver(loadingUtils)
    }

    //网络请求失败
    protected open fun onNetFail(e: Throwable) {

    }

    /**
     *更改状态栏
     * @param colorId 为空表示不重写
     * @param dark
     * @param transparencyBar
     */
    protected open fun setBarColor(
        @ColorRes colorId: Int? = null,
        dark: Boolean = true,
        transparencyBar: Boolean = false,
        isAutoHeight: Boolean = true,
        titleView: ViewGroup? = null
    ) {
        colorId?.run {
            if (activity is SimpleActivity) {
                (activity as SimpleActivity).setBarColor(
                    colorId,
                    dark,
                    transparencyBar,
                    isAutoHeight,
                    titleView
                )
            }
        }
    }

}